package org.indp.mongowl.services;

import com.mongodb.MongoClient;
import org.indp.mongowl.model.ConnectionProfile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 */
public class ConnectionManager {

    private static final Logger log = LoggerFactory.getLogger(ConnectionManager.class);
    private static final Map<ConnectionProfile, ServerConnection> connections = new HashMap<>();

    public static synchronized ServerConnection getServerConnection(ConnectionProfile connectionProfile) throws UnknownHostException {
        ServerConnection serverConnection = connections.get(connectionProfile);
        if (serverConnection == null) {
            serverConnection = createServerConnection(connectionProfile);
            connections.put(connectionProfile, serverConnection);
        }
        return serverConnection;
    }

    public static List<ConnectionProfile> getConnectionProfiles() {
        // todo
        return Arrays.asList(new ConnectionProfile(), new ConnectionProfile("localhost", 59999));
    }

    private static ServerConnection createServerConnection(ConnectionProfile connectionProfile) throws UnknownHostException {
        log.info("Connecting to {}:{}", connectionProfile.getHost(), connectionProfile.getPort());
        MongoClient mongoClient = new MongoClient(connectionProfile.getHost(), connectionProfile.getPort());
        return new ServerConnection(connectionProfile, mongoClient);
    }

    public static synchronized void destroy() {
        log.info("Destroying ConnectionManager");
        for (ServerConnection serverConnection : connections.values()) {
            try {
                serverConnection.getMongoClient().close();
            } catch (Exception e) {
                ConnectionProfile profile = serverConnection.getConnectionProfile();
                log.warn("Failed to close connection to " + profile.getHost() + ":" + profile.getPort(), e);
            }
        }
    }
}
